package com.example.art_cloud_backend.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.example.art_cloud_backend.exception.ErrorCode;
import com.example.art_cloud_backend.exception.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Author caiya
 * @Description 本地图片文件上传
 * @Version 1.0
 */
@Service
public class FilePictureUpload extends PictureUploadTemplate {
    @Override
    public void validatePicture(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空");
        // 校验文件大小
        long fileSize = multipartFile.getSize();
        final long ONE_M = 1024 * 1024L; // 1m
        ThrowUtils.throwIf(fileSize > (2 * ONE_M), ErrorCode.PARAMS_ERROR, "文件大小不能超过2MB");
        // 校验文件类型
        String fileType = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 允许的文件后缀
        final List<String> ALLOW_FORMMAT_LIST = Arrays.asList("jpeg", "png", "jpg", "webp");
        ThrowUtils.throwIf(!ALLOW_FORMMAT_LIST.contains(fileType), ErrorCode.PARAMS_ERROR, "文件类型错误");
    }

    @Override
    public String getOriginFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }

    @Override
    public void processFile(Object inputSource, File file) throws IOException {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        multipartFile.transferTo(file);
    }
}
